package com.zs4sdk.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.library.image.MultiImageSelectorActivity;
import com.common.library.util.ActivityHelper;
import com.common.library.util.Helper;

import java.util.ArrayList;

/**
 * 图片选择  写法太过丑陋有时间需要重新写(用GridView重构)
 * Created by Jancy on 16/5/19.
 */
public class Zs4GameSelectImageActivity extends Zs4GameBaseActivity {

    private ArrayList<String> mSelectPath = null;

    GridView mGridView;
    private SdkSelectImageAdapter sdkSelectImageAdapter;


    public final static int FILECHOOSER_RESULTCODE= 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(ActivityHelper.getLayoutResId("zs4gamelayout_act_select_image"));

        getParams();

        init();

    }

    @Override
    protected void init(){

        initReferences();

        sdkSelectImageAdapter = new SdkSelectImageAdapter(this);

        mGridView.setAdapter(sdkSelectImageAdapter);

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                if(Helper.isNotNull(sdkSelectImageAdapter)) {
                    if (mSelectPath.size() < 5 && position == mSelectPath.size()) {
//                        ActivityHelper.showToast("进入选择图片");
                        selectImage();
                    }
                }
            }
        });

    }

    private void  getParams(){
        Intent intent = getIntent();
        if (Helper.isNotNull(intent)) {
            if (intent.hasExtra(MultiImageSelectorActivity.EXTRA_RESULT)) {
                mSelectPath = intent.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            }else {
                mSelectPath = null;
            }
        }
    }

    /**
     * function: 初始化引用
     */
    private void initReferences() {
        mGridView = findView(GridView.class,ActivityHelper.getIdResId("zs4gameviewid_gdv_select_image"));

        setViewClickEvent(this,
                ActivityHelper.getIdResId("zs4gameviewid_btn_ensure_select"),
                ActivityHelper.getIdResId("zs4gameviewid_imb_colse_select_image"));

    }

    @Override
    public void onClick(View v) {

        super.onClick(v);
        if (v.getId() == ActivityHelper.getIdResId("zs4gameviewid_btn_ensure_select")||v.getId() == ActivityHelper.getIdResId("zs4gameviewid_imb_colse_select_image")) {
            Intent intent=new Intent();
            intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT,mSelectPath);
            setResult(RESULT_OK, intent);
            finish();
        }
    }

    private void selectImage(){
        Intent intent = new Intent(this, MultiImageSelectorActivity.class);
        // 是否显示拍摄图片
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, false);
        // 最大可选择图片数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 5);
        // 选择模式
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
        // 默认选择
        if (mSelectPath != null && mSelectPath.size() > 0) {
            intent.putExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, mSelectPath);
        }
        startActivityForResult(intent, FILECHOOSER_RESULTCODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
        if (requestCode == FILECHOOSER_RESULTCODE) {
            if (resultCode == Activity.RESULT_OK) {
                if (intent == null) {
                } else {
                    mSelectPath = intent.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                    sdkSelectImageAdapter.notifyDataSetChanged();
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    public class SdkSelectImageAdapter extends BaseAdapter {


        public  final int SET_IMAGE = 1;
        LayoutInflater inflater;

        public SdkSelectImageAdapter(Context ctx) {
            inflater = LayoutInflater.from(ctx);
        }

        @Override
        public int getCount() {
            if(Helper.isNotNull(mSelectPath)) {
                if (mSelectPath.size() < 5) {
                    return mSelectPath.size() + 1;
                }
                return mSelectPath.size();
            }else {
                return 1;
            }
        }

        @Override
        public Object getItem(int position) {

            return mSelectPath.get(position);
        }

        @Override
        public long getItemId(int position) {

            return position;
        }


        @Override
        public View getView(final int position, View convertView, final ViewGroup parent) {
            String item;
            if(position <mSelectPath.size()){
                item = mSelectPath.get(position);
            }else {
                item = "";
            }

            if (null == convertView) {
                convertView = inflater.inflate(ActivityHelper.getLayoutResId("zs4gamelayout_select_image"), null);
            }

            ImageView mImageView = (ImageView) convertView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_image"));
            ImageView deleteImage = (ImageView) convertView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_mDeleteView_view_listitem"));

            deleteImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mSelectPath.remove(position);
                    sdkSelectImageAdapter.notifyDataSetChanged();
                }
            });

            TextView mTextView = (TextView) convertView.findViewById(ActivityHelper.getIdResId("zs4gameviewid_txv_add_image"));
           setImageView(mImageView,deleteImage,mTextView,item);
            return convertView;
        }

        private void setImageView(ImageView imageView,ImageView deleteImage,TextView textView,String item){

            if(item.isEmpty()){

                deleteImage.setVisibility(View.GONE);
                textView.setVisibility(View.VISIBLE);
            }else {
                deleteImage.setVisibility(View.VISIBLE);
                textView.setVisibility(View.GONE);
            }
                Message message = new Message();

                message.what = SET_IMAGE;
                message.obj = imageView;
                Bundle mBundle = new Bundle();
                mBundle.putString("set_image",item);
                message.setData(mBundle);
                myHandler.sendMessage(message);

        }

        Handler myHandler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case SET_IMAGE:
                        ImageView mImageView = (ImageView) msg.obj;
                        Bundle bundle = msg.getData();
                        String path = bundle.getString("set_image");
//                        Log.e("path",path);
                        if(path.isEmpty()){
                            mImageView.setImageDrawable(ActivityHelper.getDrawableByName("zs4gameicon_imv_add_image"));
                        }else {
                            Bitmap bitmap = Helper.getimage(path);
                            if(bitmap.getHeight()>bitmap.getWidth()){
                                mImageView.setImageBitmap(Bitmap.createBitmap(bitmap,0,(bitmap.getHeight()/2 - bitmap.getWidth()/2),bitmap.getWidth(),bitmap.getWidth()));
                            }else {
                                mImageView.setImageBitmap(Bitmap.createBitmap(bitmap,(bitmap.getWidth()/2 - bitmap.getHeight()/2),0,bitmap.getHeight(),bitmap.getHeight()));
                            }
                        }
                        break;
                }
                super.handleMessage(msg);
            }
        };
    }
}
